<template>
    <el-drawer v-model="showDialog" title="会员详情" direction="rtl" :before-close="handleClose" class="member-detail-drawer">
        <div class="main-container" v-loading="loading">
            <el-tabs v-model="activeName" class="pb-[10px]" @tab-change="handleClick">
                <el-tab-pane label="会员信息" name="member" />
                <el-tab-pane label="可用积分账户" name="commission" />
                <el-tab-pane label="团队信息" name="team" />
                <el-tab-pane label="月份业绩" name="month" />
            </el-tabs>

            <el-form class="page-form" :model="formData" label-width="100px" ref="formRef" label-position="left" v-if="activeName == 'member'">
                <div class="text-[14px] min-w-[110px] border-solid border-l-[3px] border-[var(--el-color-primary)] pl-[5px]">基础信息</div>
                <div class="flex px-[30px] mt-[20px] mb-[20px]">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="头像">
                                <div class="input-width">
                                    <el-image v-if="formData.headimg" class="w-[70px] h-[70px]" :src="img(formData.headimg)" fit="contain">
                                        <template #error>
                                            <div class="image-slot">
                                                <img class="w-[70px] h-[70px] rounded-full" src="@/app/assets/images/member_head.png" alt="">
                                            </div>
                                        </template>
                                    </el-image>
                                    <img class="w-[70px] h-[70px] rounded-full" v-else src="@/app/assets/images/member_head.png" alt="">
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="用户名">
                                <div class="input-width">
                                    <span :title="formData.username" class="multi-hidden">{{ formData.username }}</span>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="手机号">
                                <div class="input-width">
                                    <span>{{formData.mobile}}</span>
                                </div>
                            </el-form-item>
                        </el-col>
                            <el-col :span="8">
                            <el-form-item label="会员编号">
                                <div class="input-width">
                                    <span>{{formData.member_no}}</span>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="会员等级">
                                <div class="cursor-pointer price-wrap input-width" @click="editLevelEvent(row)">
                                    <span>{{formData.fenxiao_level?.level_name || '--'}}</span>
                                    <el-icon class="ml-[5px]" :size="14"><EditPen /></el-icon>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="上级">
                                {{formData.parent_member?.username || '无'}}
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <div class="text-[14px] min-w-[110px] border-solid border-l-[3px] border-[var(--el-color-primary)] pl-[5px]">账户统计</div>
                <div class="flex px-[30px] mt-[20px] mb-[20px]">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="累计余额">
                                <div class="input-width">
                                    <span>{{moneyFormat(formData.balance_get)}}元</span>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="兑换券">
                                <div class="input-width">
                                    <span>{{moneyFormat(formData.gold_coupon)}}</span>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="贡献值">
                                <div class="input-width">
                                    <span>{{moneyFormat(formData.contribution_points)}}</span>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="可用积分">
                                <div class="input-width">
                                    <span>{{moneyFormat(formData.available_points)}}</span>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="累计消费金额">
                                <div class="input-width">
                                    <span>{{moneyFormat(formData.total_consume)}}元</span>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="团队消费金额">
                                <div class="input-width">
                                    <span>{{moneyFormat(formData.total_team_consume)}}元</span>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
            <div v-if="activeName == 'commission'">
                <el-table :data="fenxiaoAccount.data" size="large" v-loading="fenxiaoAccount.loading">
                    <template #empty>
                        <span>{{ !fenxiaoAccount.loading ? '暂无数据' : '' }}</span>
                    </template>
                    <el-table-column prop="amount" label="变动积分" min-width="120">
                        <template #default="{ row }">
                            <span v-if="row.amount.indexOf('-') != -1" class="text-[#f00]">{{ row.amount }}</span>
                            <span v-else class="text-[#00a854]">+{{ row.amount }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="账户来源" min-width="120">
                        <template #default="{ row }">
                            <Dict-tag :value="row.type" :list="pointChangeTypeList" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="after_amount" label="可用积分" min-width="120" />
                    <el-table-column prop="create_time" label="创建时间" min-width="120" />
                </el-table>
                <div class="mt-[16px] flex justify-end">
                    <el-pagination v-model:current-page="fenxiaoAccount.page" v-model:page-size="fenxiaoAccount.limit"
                        layout="total, sizes, prev, pager, next, jumper" :total="fenxiaoAccount.total"
                        @size-change="getFenxiaoAccountFn()" @current-change="getFenxiaoAccountFn" />
                </div>
            </div>
            <div v-if="activeName == 'team'">
                <el-table :data="fenxiaoTeam.data" size="large" v-loading="fenxiaoTeam.loading">
                    <template #empty>
                        <span>{{ !fenxiaoTeam.loading ? '暂无数据'  : '' }}</span>
                    </template>
                    <el-table-column label="账户信息" min-width="120">
                        <template #default="{ row }">
                            <div class="flex items-center">
                                <div class="min-w-[50px] h-[50px] flex items-center justify-center">
                                    <el-image v-if="row.headimg && row.headimg" class="w-[50px] h-[50px]" :src="img(row.headimg)" fit="contain">
                                        <template #error>
                                            <div class="image-slot">
                                                <img class="w-[50px] h-[50px] rounded-full" src="@/app/assets/images/member_head.png" alt="">
                                            </div>
                                        </template>
                                    </el-image>
                                    <img class="w-[50px] h-[50px] rounded-full" v-else src="@/app/assets/images/member_head.png" alt="">
                                </div>
                                <div class="ml-2">
                                    <span :title="row.username" class="multi-hidden">{{row.username || '--'}}</span>
                                    <span class="text-[12px]">{{row.mobile || '--'}}</span>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="等级" min-width="150">
                        <template #default="{ row }">
                            <div>{{ row.fenxiao_level?.level_name || '--' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="业绩" min-width="150">
                        <template #default="{ row }">
                            <div>{{ row.total_team_consume || '--' }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="加入时间" min-width="150">
                        <template #default="{ row }">
                            <div>{{ row.create_time || '--'  }}</div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="mt-[16px] flex justify-end">
                    <el-pagination v-model:current-page="fenxiaoTeam.page" v-model:page-size="fenxiaoTeam.limit"
                        layout="total, sizes, prev, pager, next, jumper" :total="fenxiaoTeam.total"
                        @size-change="getFenxiaoTeamFn()" @current-change="getFenxiaoTeamFn" />
                </div>
            </div>
            <div v-if="activeName == 'month'">
                <el-table :data="monthData.data" size="large" v-loading="monthData.loading">
                    <template #empty>
                        <span>{{ !monthData.loading ? '暂无数据'  : '' }}</span>
                    </template>
                    <el-table-column prop="stat_month" label="月份" />
                    <el-table-column prop="big_area" label="大区业绩" />
                    <el-table-column prop="small_area" label="小区业绩" />
                </el-table>
                <div class="mt-[16px] flex justify-end">
                    <el-pagination v-model:current-page="monthData.page" v-model:page-size="monthData.limit"
                        layout="total, sizes, prev, pager, next, jumper" :total="monthData.total"
                        @size-change="getFenxiaoTeamFn()" @current-change="getFenxiaoTeamFn" />
                </div>
            </div>
        </div>

        <!-- 编辑等级弹窗 -->
        <el-dialog v-model="fenxiaoLevelDialog" title="编辑等级" width="470px" :destroy-on-close="true" :close-on-click-modal="false">
            <div>
                <el-form-item label="会员等级">
                    <el-select v-model="levelFormData.level_id" class="input-width" clearable placeholder="请选择等级">
                        <el-option v-for="item in levelList" :key="item.value" :label="item.level_name" :value="item.level_id" />
                    </el-select>
                    <span class="text-[var(--el-color-primary)] ml-[10px] cursor-pointer" @click="getFenxiaoLevelListFn(true)">刷新</span>
                    <span class="text-[var(--el-color-primary)] ml-[10px] cursor-pointer" @click="addLevelFn">添加等级</span>
                </el-form-item>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="fenxiaoLevelDialog=false">取消</el-button>
                    <el-button type="primary" @click="fenxiaoLevelSubmit">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 选择团队绩效奖励弹窗 -->
        <fenxiao-of-select-popup title="编辑上级" ref="fenxiaoOfSelectPopupRef" :params="params" @load="selectFenxiaoCallbackFn" />
    </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { t } from '@/lang'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useDictionary } from "@/app/api/dict";
import { img, moneyFormat } from '@/utils/common'
import { getFenxiaoInfo, getFenxiaoTeam, editFengxiao, getTeamPerformance } from '@/app/api/range'
import { getPointsLogList } from "@/app/api/distributor";
import { getFenxiaoLevelList } from '@/addon/shop_fenxiao/api/level'
import fenxiaoOfSelectPopup from '@/app/views/range/member/components/fenxiao-of-select-popup.vue'
import { cloneDeep } from 'lodash-es'

const showDialog = ref(false)
const loading = ref(false)
const router = useRouter()

const activeName = ref('member')
const formData: any = ref({})
let id = ''

const emit = defineEmits(['load'])

const handleClose = (done: () => void) => {
    emit('load');
    activeName.value = 'member';
    showDialog.value = false;
}

const handleClick = (data: any) => {
    activeName.value = data
}

// 佣金账户明细
const fenxiaoAccount = reactive({
    page: 1,
    limit: 10,
    total: 0,
    loading: false,
    data: []
})
// 团队绩效奖励团队
const fenxiaoTeam = reactive({
    page: 1,
    limit: 10,
    total: 0,
    loading: false,
    data: [],
})

const monthData = reactive<any>({
    page: 1,
    limit: 10,
    total: 0,
    loading: false,
    data: []
})

// 获取本月业绩
const getMonthData = (id: any) => {
    monthData.loading = true
    getTeamPerformance(id, {
        page: monthData.page,
        limit: monthData.limit
    }).then((res: any) => {
        monthData.data = res.data.data
        monthData.total = res.data.total
    }).finally(() => {
        monthData.loading = false
    })
}

const getDetail = (id: number) => {
    loading.value = true
    getFenxiaoInfo(id).then((res: any) => {
        formData.value = res.data
        loading.value = false
    }).catch(() => {
        loading.value = false
    })
}

const getFenxiaoAccountFn = () => {
    fenxiaoAccount.loading = true
    getPointsLogList({
        page: fenxiaoAccount.page,
        limit: fenxiaoAccount.limit,
        points_type: 2,
        member_id: id
    }).then((res:any) => {
        fenxiaoAccount.data = res.data.data
        fenxiaoAccount.total = res.data.total
        fenxiaoAccount.loading = false
    }).catch(() => {
        fenxiaoAccount.loading = false
    })
}

const getFenxiaoTeamFn = (page: number = 1) => {
    fenxiaoTeam.loading = true
    fenxiaoTeam.page = page
    getFenxiaoTeam({
        page: fenxiaoTeam.page,
        limit: fenxiaoTeam.limit,
        member_id: id
    }).then((res:any) => {
        fenxiaoTeam.data = res.data.data
        fenxiaoTeam.total = res.data.total
        fenxiaoTeam.loading = false
    }).catch(() => {
        fenxiaoTeam.loading = false
    })
}

const params:Record<string, any> = reactive({
    member_id: formData.member_id,
    is_agent: 'all'
})
const resetFormInfo = () => {
    const data = cloneDeep(formData.value)
    levelFormData.id = data.member_id
    levelFormData.level_id = data.level_id
    levelFormData.parent = data.parent
    params.member_id = data.member_id
    levelFormData.status = data.status
}

/******************* 上级团队绩效奖励弹框start *************************/
// 选择上级团队绩效奖励弹框
const fenxiaoOfSelectPopupRef = ref<any>()
const editSupEvent = (row:any) => {
    resetFormInfo()
    fenxiaoOfSelectPopupRef.value?.show()
}
// 选择回调
const selectFenxiaoCallbackFn = (row: any) => {
    if (row && row.member_id) {
        levelFormData.parent = row.member_id
        levelFormData.parent_name = row.username
    } else {
        levelFormData.parent = null
        levelFormData.parent_name = null
    }
    ElMessageBox.confirm('确认要变更上级吗', '提示',
        {
            confirmButtonText: t('confirm'),
            cancelButtonText: t('cancel'),
            type: 'warning'
        }
    ).then(() => {
        fenxiaoSubmit()
    })
}
/******************* 上级团队绩效奖励弹框end *************************/

/******************* 团队绩效奖励等级弹框start *************************/
const levelList = ref([])
const levelFormData: Record<string, any> = reactive({
    id: 0,
    level_id: null,
    parent: null,
    status: 1
})
// 获取分销等级
const getFenxiaoLevelListFn = (bool=false) => {
    getFenxiaoLevelList({
        page: 1,
        limit: 11,
        type: 2
    }).then((res:any) => {
        levelList.value = res.data.data
        if(bool){
            ElMessage.success('刷新成功')
        }
    })
}
getFenxiaoLevelListFn()

const fenxiaoLevelDialog = ref(false)
const editLevelEvent = (data:any) => {
    resetFormInfo();
    fenxiaoLevelDialog.value = true
}

// 编辑分销等级回调
const fenxiaoLevelSubmit = () => {
    fenxiaoLevelDialog.value = false
    if (!levelFormData.level_id) {
        ElMessage.error('请选择等级')
        return
    }
    fenxiaoSubmit()
}
const fenxiaoSubmit = () => {
    editFengxiao(levelFormData).then(() => {
        getDetail(id)
    })
}

// 跳转分销等级列表页面
const addLevelFn = () => {
    const routeData = router.resolve('/shop_fenxiao/management/level')
    window.open(routeData.href, '_blank')
}
/******************* 团队绩效奖励等级弹框end *************************/
const pointChangeTypeList = ref<any[]>([]);

const setFormData = (row: any = null) => {
    id = row.id;
    getDetail(row.id)
    getFenxiaoAccountFn()
    getFenxiaoTeamFn()
    getMonthData(row.id)
    useDictionary("point_change_type").then((res: any) => {
        pointChangeTypeList.value = res.data.dictionary;
    });
}

defineExpose({
    showDialog,
    setFormData
})
</script>

<style lang="scss">
.member-detail-drawer{
    width: 1000px !important;
}
</style>
